<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
            class="input-with-select"
            v-model="queryInfo.query"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户信息表格 -->
      <el-table :data="userList" style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="mobile" label="手机" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 插槽  scope可以获取到这列单元格的信息-->
          <template slot-scope="scope">
            <el-switch @change="changeStatus(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editUser(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delUser(scope.row)"></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              :enterable="false"
              placement="top"
            >
              <el-button type="warning" icon="el-icon-setting" @click="openRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分配角色 -->
      <el-dialog @close="closeRole" title="分配角色" :visible.sync="dialogVisibleRole" width="50%">
        <div>
          <p>用户名称：{{userInfo.username}}</p>
          <p>用户角色：{{userInfo.role_name}}</p>
          <p>
            设置角色：
            <el-select v-model="roleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleRole = false">取 消</el-button>
          <el-button type="primary" @click="setRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 新增用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeForm('userFormRef')"
    >
      <!-- 表单 -->
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="edClose()">
      <!-- 表单 -->
      <el-form
        :model="updateFrom"
        :rules="editUserRules"
        ref="upFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input :disabled="true" v-model="updateFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="updateFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    //自定义校验规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (!regEmail.test(value)) {
        callback(new Error("请输入合法的邮箱"));
      }
      callback();
    };
    var checkMobil = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regMobil = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (!regMobil.test(value)) {
        callback(new Error("请输入合法的手机号"));
      }
      callback();
    };
    return {
      //选中的角色id
      roleId:'',
      //角色列表
      roleList:[],
      //分配角色按钮点击
      userInfo: {},
      //分配角色对话框
      dialogVisibleRole: false,
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      //展示数据
      userList: [],
      //总条数
      total: 0,
      dialogVisible: false,
      editDialogVisible: false,
      userForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      updateFrom: {
        username: "",
        email: "",
        mobile: ""
      },

      userFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobil, trigger: "blur" }
        ]
      },
      editUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobil, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //点击确定按钮分配角色
    async setRole(){
      const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.roleId})
      if(res.meta.status!==200)return this.$message.error('设置角色失败');
      this.$message.success('设置成功');
      this.getUserList();
      this.dialogVisibleRole=false;
    },
    //关闭分配角色对话框
    closeRole(){
      this.userInfo={};
      this.roleId='';
    },
    //分配角色按钮点击
    async openRole(userInfo) {
      this.userInfo = userInfo;
      //发送请求获取角色列表
      const {data:res} = await this.$http.get('roles');
      if(res.meta.status!==200)return this.$message.error('获取角色列表失败');
      this.roleList=res.data;
      this.dialogVisibleRole = true;
    },
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    async changeStatus(user) {
      const { data: res } = await this.$http.put(
        `users/${user.id}/state/${user.mg_state}`
      );
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state;
        return this.$message.error("设置状态失败");
      }
      this.$message.success("设置状态成功");
    },
    closeForm() {
      this.$refs.userFormRef.resetFields();
    },
    edClose() {
      this.$refs.upFormRef.resetFields();
    },
    addUser() {
      this.$refs.userFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post("users", this.userForm);
          if (res.meta.status !== 201) {
            return this.$message.error("添加失败");
          }
          this.$message.success("添加成功");
          this.dialogVisible = false;
          this.getUserList();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async editUser(userInfo) {
      //根据id查询用户
      const { data: res } = await this.$http.get(`users/${userInfo.id}`);
      this.updateFrom = res.data;
      this.passShow = false;
      this.userDisable = true;
      this.editDialogVisible = true;
    },
    updateUser() {
      this.$refs.upFormRef.validate(async valid => {
        if (!valid) return false;
        //通过上面的请求查询到了Id
        const { data: res } = await this.$http.put(
          "users/" + this.updateFrom.id,
          this.updateFrom
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败");
        }
        this.$message.success("修改成功");
        this.editDialogVisible = false;
        this.getUserList();
      });
    },
    delUser(userInfo) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${userInfo.id}`);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.getUserList();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>
<style scoped>
</style>
